#include "appfactory.h"
#include "rssfactory.h"


QString AppFactory::latestVersion(const QString &url) {
	QByteArray out;
	RssFactory::downloadFileToQString(url, &out, DEF_TIMEOUT);
	QString text(out);
	int pos = text.indexOf(UPDATE_PHRASE);
	return text.mid(pos+UPDATE_PHRASE.size()+1, 5);
}

void AppFactory::setupWebSettings(QWebSettings *settings) {
    webSettings = settings;
}

void AppFactory::applyWebSettings(QWebSettings *settings, QWebView *view) {
    view->settings()->setFontFamily(QWebSettings::StandardFont,
                                    settings->fontFamily(QWebSettings::StandardFont));
    view->settings()->setFontSize(QWebSettings::DefaultFontSize,
                                  settings->fontSize(QWebSettings::DefaultFontSize));
}

QSettings::Status AppFactory::checkSettings() {
    settings->sync();
    return settings->status();
}

QSettings::Status AppFactory::setupSettings() {
    QString defaultPath = APP_PATH_BASE + QDir::separator() + APP_PATH_CONFIG;
    QString appPath		= qApp->applicationDirPath() + QDir::separator() + APP_PATH_CONFIG;
    if (QFile(appPath).exists())
        settings = new QSettings(appPath, QSettings::IniFormat);
    else
        settings = new QSettings(defaultPath, QSettings::IniFormat);
    return checkSettings();
}

QString AppFactory::getNetCodeError(QNetworkReply::NetworkError code) {
    switch (code) {
        case QNetworkReply::ProtocolFailure:
			return QObject::tr("Feed is not well-formed.");
        case QNetworkReply::HostNotFoundError:
        case QNetworkReply::RemoteHostClosedError:
        case QNetworkReply::ConnectionRefusedError:
			return QObject::tr("This feed wasn't reached.");
        case QNetworkReply::TimeoutError:
        case QNetworkReply::ProxyTimeoutError:
            return QObject::tr("Connection to feed timed out.");
        case QNetworkReply::SslHandshakeFailedError:
            return QObject::tr("Feed updating failed. RSSG wasn't able to obtain SSL certificate.");
		case QNetworkReply::ProxyConnectionClosedError:
		case QNetworkReply::ProxyConnectionRefusedError:
			return QObject::tr("Proxy server connection refused or closed.");
		case QNetworkReply::TemporaryNetworkFailureError:
			return QObject::tr("Feed is temporarily unavailable.");
		case QNetworkReply::ProxyAuthenticationRequiredError:
			return QObject::tr("This feed requires proxy athentification.");

		case QNetworkReply::ProxyNotFoundError:
			return QObject::tr("Proxy server was not found.");
        default:
            /*
            QNetworkReply::OperationCanceledError
            QNetworkReply::TemporaryNetworkFailureError
            QNetworkReply::ContentAccessDenied
            QNetworkReply::ContentOperationNotPermittedError
            QNetworkReply::ContentNotFoundError
            QNetworkReply::AuthenticationRequiredError
            QNetworkReply::ContentReSendError
            QNetworkReply::ProtocolUnknownError
            QNetworkReply::ProtocolInvalidOperationError
			QNetworkReply::UnknownNetworkError
            QNetworkReply::UnknownProxyError
            QNetworkReply::UnknownContentError
            */
            return QObject::tr("Connection to feed failed.");
    }
}

void AppFactory::setApplicationProxy() {
    AppFactory::settings->beginGroup("Proxy");
    int proxyType = AppFactory::settings->value("proxyType", 0).toInt();
    if (!proxyType) {
        QNetworkProxyFactory::setUseSystemConfiguration(false);
        QNetworkProxy::setApplicationProxy(QNetworkProxy::NoProxy);
        qDebug() << QString("%1 Setting proxy to QNetworkProxy::NoProxy").arg(APP_ID);
    }
    else if (proxyType == 1) {
        QNetworkProxyFactory::setUseSystemConfiguration(true);
        qDebug() << QString("%1 Setting proxy to QNetworkProxy::DefaultProxy").arg(APP_ID);
    }
    else {
        QNetworkProxy proxy;
        QNetworkProxy::ProxyType type;
        switch (proxyType) {
            case 2:
                type = QNetworkProxy::Socks5Proxy;
                break;
            case 3:
                type = QNetworkProxy::HttpProxy;
                break;
        }
        proxy.setType(type);
        QNetworkProxyFactory::setUseSystemConfiguration(false);
        proxy.setHostName(AppFactory::settings->value("proxyHost").toString());
        proxy.setPort(AppFactory::settings->value("proxyPort", 80).toInt());
        proxy.setUser(AppFactory::settings->value("proxyName").toString());
        proxy.setPassword(AppFactory::settings->value("proxyPass").toString());
        qDebug() << QString("%1Setting proxy %2 on port %3").arg(APP_ID, proxy.hostName(), QString::number(proxy.port()));
        QNetworkProxy::setApplicationProxy(proxy);
    }
    AppFactory::settings->endGroup();
}


//////////////
// HTML Stuff
//////////////

QString AppFactory::deEscape(const QString &html) {
	QMap<QString, QString> sequences;
	sequences["&lt;"]		= "<";
	sequences["&gt;"]		= ">";
	sequences["&amp;"]		= "&";
	sequences["&quot;"]		= "\"";
	sequences["&nbsp;"]		= " ";
	sequences["&plusmn;"]	= "±";
	sequences["&times;"]	= "×";

	QList<QString> keys = sequences.uniqueKeys();
	QString output = html;

	foreach (QString key, keys) {
		output.replace(key, sequences.value(key));
	}
	return output;
}

QString AppFactory::toPlainText(const QString &html) {
	return deEscape(html).replace(QRegExp("<[^>]*>"), "")/*.replace(QRegExp("[*\n]"), " ")*/;
}
